package info.xingxingdd.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import info.xingxingdd.admin.common.PageQuery;
import info.xingxingdd.admin.common.Result;
import info.xingxingdd.admin.entity.ClientUser;
import info.xingxingdd.admin.service.ClientUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 客户端用户控制器
 */
@RestController
@RequestMapping("/api/user")
public class ClientUserController {
    
    @Autowired
    private ClientUserService clientUserService;
    
    /**
     * 分页查询
     */
    @PostMapping("/page")
    public Result<IPage<ClientUser>> page(@RequestBody PageQuery query) {
        LambdaQueryWrapper<ClientUser> wrapper = new LambdaQueryWrapper<>();
        
        // 关键字查询
        if (StringUtils.hasText(query.getKeyword())) {
            wrapper.like(ClientUser::getAccount, query.getKeyword())
                   .or()
                   .like(ClientUser::getType, query.getKeyword());
        }
        
        // 按创建时间倒序排序
        wrapper.orderByDesc(ClientUser::getCreateAt);
        
        Page<ClientUser> page = new Page<>(query.getCurrent(), query.getSize());
        IPage<ClientUser> result = clientUserService.page(page, wrapper);
        
        return Result.success(result);
    }
    
    /**
     * 根据ID查询
     */
    @GetMapping("/{id}")
    public Result<ClientUser> getById(@PathVariable Integer id) {
        ClientUser user = clientUserService.getById(id);
        // 出于安全考虑，不返回密码
        if (user != null) {
            user.setPassword(null);
        }
        return Result.success(user);
    }
    
    /**
     * 新增
     */
    @PostMapping
    public Result<ClientUser> save(@RequestBody ClientUser user) {
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        user.setCreateAt(now);
        user.setUpdateAt(now);
        
        // TODO: 实际项目中应该对密码进行加密处理
        
        clientUserService.save(user);
        
        // 出于安全考虑，不返回密码
        user.setPassword(null);
        return Result.success(user);
    }
    
    /**
     * 修改
     */
    @PutMapping
    public Result<ClientUser> update(@RequestBody ClientUser user) {
        // 设置更新时间
        user.setUpdateAt(LocalDateTime.now());
        
        // TODO: 实际项目中应该对密码进行加密处理
        
        clientUserService.updateById(user);
        
        // 出于安全考虑，不返回密码
        user.setPassword(null);
        return Result.success(user);
    }
    
    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Integer id) {
        clientUserService.removeById(id);
        return Result.success();
    }
} 